package com.umeox.watch.moto.launcher.fragment

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.provider.Settings
import android.text.format.DateFormat
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeFragment
import com.umeox.moto.watch.themes.widget.ImageView
import com.umeox.moto.watch.themes.widget.TextView
import com.umeox.watch.moto.dataservice.constants.Constants
import com.umeox.watch.moto.launcher.R
import com.umeox.watch.moto.launcher.adapter.PrayerTimeListAdapter
import com.umeox.watch.moto.launcher.bean.PrayerTimeInfo
import com.umeox.watch.moto.launcher.event.DeviceStatusChangedEvent
import com.umeox.watch.moto.launcher.event.PrayerTimeListFragmentVisibleEvent
import com.umeox.watch.moto.launcher.utils.PrayerTimesCoordinator
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * Created by Rambo 2023/7/19
 * Describe:
 */
class PrayerTimeListFragment : ThemeFragment() {

    private var prayerTimeList: MutableList<PrayerTimeInfo>? = null

    private lateinit var prayerTimeListAdapter: PrayerTimeListAdapter
    private lateinit var timesRv: RecyclerView
    private lateinit var noDataIv: ImageView

    private var is24HourFormat: Boolean = false

    override fun onAttach(context: Context) {
        super.onAttach(context)
        EventBus.getDefault().register(this)
    }

    override fun onDetach() {
        super.onDetach()
        EventBus.getDefault().unregister(this)
    }


    override fun getLayoutId(): Int {
        return R.layout.fragment_prayer_time_list
    }

    override fun initView(rootView: View) {
        is24HourFormat = DateFormat.is24HourFormat(requireContext())
        timesRv = rootView.findViewById(R.id.rv_times)
        noDataIv = rootView.findViewById(R.id.no_data_iv)
        //获取本地经纬度
        val lat: String? = Settings.Global.getString(requireContext().contentResolver, "LAT")
        val long: String? = Settings.Global.getString(requireContext().contentResolver, "LONG")
        Logger.e("lat=$lat,long=$long")
        if ((!lat.isNullOrEmpty() && lat != "-999") && (!long.isNullOrEmpty() && long != "-999")) {
            calcPrayerTime(lat.toDouble(), long.toDouble())
            val prePrayerTimeIndex: Int =
                binarySearchRight(prayerTimeList!!, System.currentTimeMillis())
            Logger.e("$prayerTimeList")
            Logger.e("prePrayerTimeIndex=$prePrayerTimeIndex")

            if (prePrayerTimeIndex != -1) { //等于-1 说明当前时间是午夜后半夜，列表不需要高亮某个时刻
                prayerTimeList!![prePrayerTimeIndex].isHighLight = true
            }
            Logger.e("$prayerTimeList")
            noDataIv.visibility = View.GONE
            timesRv.visibility = View.VISIBLE

        } else {
            noDataIv.visibility = View.VISIBLE
            timesRv.visibility = View.GONE
        }

        prayerTimeListAdapter = PrayerTimeListAdapter(requireContext(),prayerTimeList, is24HourFormat)
        timesRv.adapter = prayerTimeListAdapter
        timesRv.setHasFixedSize(true)
        timesRv.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
        //timesRv.setItemViewCacheSize(7)
        timesRv.recycledViewPool.setMaxRecycledViews(0, 0)


        registerPrayerSettingChangeReceiver()
    }

    private fun registerPrayerSettingChangeReceiver() {
        val mFilter = IntentFilter()
        mFilter.addAction(Constants.ACTION_UPDATED_PRAYER_TIME)
        mFilter.addAction(Constants.ACTION_LOCATION_SUCCESS)
        requireContext().registerReceiver(mPrayerSettingChangeReceiver, mFilter)
    }


    private val mPrayerSettingChangeReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Logger.e("action=$action")
            if (action == Constants.ACTION_UPDATED_PRAYER_TIME) {  //祈祷设置发生改变，重新计算
                val lat = Settings.Global.getString(requireContext().contentResolver, "LAT")
                val long = Settings.Global.getString(requireContext().contentResolver, "LONG")
                updateList(lat, long)
            } else if (action == Constants.ACTION_LOCATION_SUCCESS) {
                val lat = intent.getStringExtra("LAT")
                val long = intent.getStringExtra("LONG")
                updateList(lat, long)
            }
        }
    }

    private fun updateList(lat: String?, long: String?) {
        Logger.e("lat=$lat,long=$long")
        if (lat.isNullOrEmpty() && long.isNullOrEmpty()) {
            return
        }

        if (lat != "-999" && long != "-999") {
            if (noDataIv.visibility == View.VISIBLE) {
                noDataIv.visibility = View.GONE
            }
            if (timesRv.visibility == View.GONE) {
                timesRv.visibility = View.VISIBLE
            }
            calcPrayerTime(lat?.toDouble()!!, long?.toDouble()!!)
            val prePrayerTimeIndex: Int =
                binarySearchRight(prayerTimeList!!, System.currentTimeMillis())

            Logger.e("prePrayerTimeIndex=$prePrayerTimeIndex")

            if (prePrayerTimeIndex != -1) { //等于-1 说明当前时间是午夜后半夜，列表不需要高亮某个时刻
                prayerTimeList!![prePrayerTimeIndex].isHighLight = true
            }
            Logger.e("$prayerTimeList")
            //更新列表
            prayerTimeListAdapter.setData(prayerTimeList!!)
        }
    }

    private fun calcPrayerTime(lat: Double, long: Double) {
        val prayerTimesCoordinator = PrayerTimesCoordinator()
        prayerTimesCoordinator.updateParameters(DateFormat.is24HourFormat(requireContext()))
        val timeZone: TimeZone = TimeZone.getDefault()
        val time = timeZone.rawOffset //获取时差，返回值毫秒
        prayerTimeList = prayerTimesCoordinator.getPrayerTimeData(
            lat,
            long,
            (time / 1000 / 60 / 60).toDouble()
        )

        prayerTimeList!!.removeAt(prayerTimeList?.size!! - 1)
    }


    //找到<=target最右的位置
    private fun binarySearchRight(arr: MutableList<PrayerTimeInfo>, target: Long): Int {
        var left = 0
        var right = arr.size - 1
        var result = -1
        while (left <= right) {
            val middle = left + (right - left shr 1)
            if (arr[middle].timestamp <= target) {
                result = middle
                left = middle + 1
            } else {
                right = middle - 1
            }
        }
        return result
    }

    override fun onDestroyView() {
        super.onDestroyView()
        try {
            requireContext().unregisterReceiver(mPrayerSettingChangeReceiver)
        } catch (ignored: Exception) {

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFragmentVisible(event: PrayerTimeListFragmentVisibleEvent) {
        Logger.e("==========>onFragmentVisible")
        val lat = Settings.Global.getString(requireContext().contentResolver, "LAT")
        val long = Settings.Global.getString(requireContext().contentResolver, "LONG")
        updateList(lat, long)
    }
}